/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/
 
import fever.data.validators.Validator;
import fever.data.validators.ValidatorStrategy;
import fever.events.ValidationResultEvent;
import fever.utils.StringUtil;

/**
 * Validates Email address.
 * 
 * <p>Default use a simple string validation ( '@' place, char length and more ).<br />
 * You can use more precise validation process using the {@link #strategy} property.<br />
 * 
 * <p>Note : If {@link fever.data.validators.EmailValidatorStrategy} is used, all others tests 
 * are ignored.
 * 
 * <p>All strategy classes must implement
 * {@link fever.data.validators.EmailValidatorStrategy} interface.
 * 
 * <p>Example
 * {@code
 * public function ValidationTest5()
 * {
 *  var email : String = "myname@myDo";
 * 		
 * 	var validator : EmailValidator = new EmailValidator();
 * 	validator.strategy = new RegExpStategy();
 * 	
 *  var result : ValidationResultEvent = validator.validate(email);
 *  if(result.type == ValidationResultEvent.INVALID)
 *  {
 *    Logger.LOG(result.message, LogLevel.WARN, FeverDebug.channel);	
 *  }
 *  else
 *  {
 *    Logger.LOG("Nice !", LogLevel.WARN, FeverDebug.channel);
 *  }
 * }
 * }
 * 
 * @see fever.data.validators.Validator
 * @see fever.data.validators.email.AS2LibEmailStrategy
 * @see fever.data.validators.email.JSEmailStrategy
 * 
 * @author Romain Ecarnot
 */
class fever.data.validators.EmailValidator extends Validator
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var PROHIBITED_CHARS : Array = [
			" ", "\n", "\r", "\t", "/", "(", ")", "[", "]", "|", "'", "~",
			"&", "=", "!", ";", "%", "¨", "+", "#", ">", "<"
			];
	
	
	//-------------------------------------------------------------------------
	// Public properties
	//-------------------------------------------------------------------------
	
	/** Strategy to use for email validation. ( default is {@code null} ). */
	public var strategy : ValidatorStrategy;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor.
	 */
	public function EmailValidator( emailStrategy : ValidatorStrategy )
	{
		if( emailStrategy ) strategy = emailStrategy;
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private function _doValidation( object ) : ValidationResultEvent
	{
		var email : String = _buildValidationTarget( object );
		
		if( !_testRequired( email ) )
		{	
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( strategy != null )
		{
			if( !strategy.validate( email ) )
			{
				_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_invalid_email_error );
				_fireEventType( ValidationResultEvent.INVALID );
				return _event;
			}
			else
			{
				_prepareEvent( ValidationResultEvent.VALID, email, '' );
				_fireEventType( ValidationResultEvent.VALID );
				return _event;
			}			
		}
		
		if( email.indexOf( '@' ) < 0 ) 
		{
			_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_missing_at_sign_error );
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( email.split( '@' ).length > 2 )
		{	
			_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_too_many_at_sign_error );
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( email.lastIndexOf( '.' ) > email.length - 3 || email.indexOf(".") < 3 )
		{	
			_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_invalid_domain_error );
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		if( email.indexOf( '@' ) == 0 )
		{
			_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_missing_username_error );
			_fireEventType( ValidationResultEvent.INVALID );
			return _event;
		}
		
		var i = 27;
		while( --i > 0 )
		{
			if( StringUtil.contains( email, PROHIBITED_CHARS[i] ) )	
			{
				_prepareEvent( ValidationResultEvent.INVALID, email, _resources.mail_invalid_char_error );
				_fireEventType( ValidationResultEvent.INVALID );
				return _event;	
			}
		}
		
		_prepareEvent( ValidationResultEvent.VALID, email, '');
		_fireEventType( ValidationResultEvent.VALID );
		
		return _event;
	}
	
}